package what.basic.chooser;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.filechooser.FileFilter;;
public class Jfilefilter implements ActionListener {
	JFrame f=null;
	JLabel lbl=null;
	JFileChooser fc=null;
	public Jfilefilter(){
		f=new JFrame ("filefilterdemo");
		Container cp=f.getContentPane();
		JButton b=new JButton("open file");
		b.addActionListener(this);
		lbl=new JLabel(" ",JLabel.CENTER);
		lbl.setPreferredSize(new Dimension(150,30));
		cp.add(lbl,BorderLayout.CENTER);
		cp.add(b,BorderLayout.SOUTH);
		f.pack();
		f.setVisible(true);
		f.addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		});
	}
	public static void main(String[] args) {
		new Jfilefilter();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		fc=new JFileChooser("c:\\winnt");
		fc.addChoosableFileFilter(new JAVAFileFilter("class"));
		fc.addChoosableFileFilter(new JAVAFileFilter("java"));
		int result=fc.showOpenDialog(f);
		if(result==JFileChooser.APPROVE_OPTION){
			File file=fc.getSelectedFile();
			lbl.setText("you selected:"+file.getName());
		}
		else if(result==fc.CANCEL_OPTION){
			lbl.setText("you did not select file");
		}	
	}
}
class JAVAFileFilter extends FileFilter{
	String ext;
	public JAVAFileFilter(String ext){
		this.ext=ext;
	}
	public boolean accept(File file) {
		if(file.isDirectory()){return true;
		
		}
		String filename=file.getName();
		int index=filename.lastIndexOf('.');
		if(index>0 && index<filename.length()-1){
			String extension=filename.substring(index+1).toLowerCase();
			if(extension.equals(ext))
				return true;
		}
		return false;
	}
	public String getDescription(){
		if(ext.equals("java"))
			return "JAVA Source File(*.java)";
		if(ext.equals("class"))
			return "JAVA Class File(*.class)";
		return "";
	}
}